using Dapper;
using MediatR;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.ERP.SalesManagement.H;
using RBAC.Read.Api.Application.Dto.ERP.SalesManagement.H;

namespace RBAC.Read.Api.Application.Handler.ERP.SalesManagement.H
{
    public class GetSalesOrderKpiHandler : IRequestHandler<GetSalesOrderKpiCommand, APIResult<GetSalesOrderKpiDto>>
    {
        private readonly IDbConnectionFactory _db;
        public GetSalesOrderKpiHandler(IDbConnectionFactory db)
        {
            _db = db;
        }

        public async Task<APIResult<GetSalesOrderKpiDto>> Handle(GetSalesOrderKpiCommand request, CancellationToken cancellationToken)
        {
            try
            {
                if (request.Days != 7 && request.Days != 30 && request.Days != 365)
                    request.Days = 7;
                var groupBy = (request.GroupBy ?? "day").ToLowerInvariant();
                if (groupBy != "day" && groupBy != "month") groupBy = "day";

                using var conn = _db.CreateConnection();
                var p = new DynamicParameters();
                p.Add("@StartDate", DateTime.Now.Date.AddDays(-request.Days + 1));

                string labelExpr = groupBy == "month" ? "DATE_FORMAT(so.OrderDate, '%Y-%m')" : "DATE_FORMAT(so.OrderDate, '%Y-%m-%d')";
                string groupExpr = groupBy == "month" ? "DATE_FORMAT(so.OrderDate, '%Y-%m')" : "DATE(so.OrderDate)";

                var sql = $@"
SELECT 
  {labelExpr} AS Label,
  COUNT(DISTINCT so.Id) AS OrderCount,
  IFNULL(SUM(IFNULL(sod.Num,0) * IFNULL(sod.Price,0)), 0) AS SalesAmount
FROM SalesOrder so
LEFT JOIN SalesOrderDetail sod ON so.Id = sod.SalesOrderId
WHERE so.OrderDate >= @StartDate
GROUP BY {groupExpr}
ORDER BY {groupExpr} ASC";

                var rows = await conn.QueryAsync<SalesOrderKpiPoint>(sql, p);
                var dto = new GetSalesOrderKpiDto { Points = rows.ToList() };

                return new APIResult<GetSalesOrderKpiDto>
                {
                    Code = APIEnums.Success,
                    Msg = "查询成功",
                    Data = dto
                };
            }
            catch (Exception ex)
            {
                return new APIResult<GetSalesOrderKpiDto>
                {
                    Code = APIEnums.Error,
                    Msg = $"查询失败: {ex.Message}",
                    Data = default
                };
            }
        }
    }
}
